<?php
# @Author: 魏巍 <jswei>
# @Date:   2017-11-16T17:42:05+08:00
# @Email:  524314430@qq.com
# @Last modified by:   魏巍
# @Last modified time: 2017-12-11T14:58:28+08:00



namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\App;
use think\facade\Session;

class Base extends Controller
{
    protected static $mc_id = '';
    protected static $setting = null;
    protected $needLogin = true;
    public function __construct(App $app = null){
        parent::__construct($app);
        header('Content-type:text/html;charset=utf-8;');
        set_time_limit(0);
        self::$mc_id = \session('mc_id');
//        p(\session(''));die;
        //常用变量
        $this->assign('action',strtolower(request()->action()));
        $this->assign('controller',strtolower(request()->controller()));
        $this->assign('module',strtolower(request()->module()));
        //判断是否登录
        $this->check_priv();
//        $this->system =$this->_sys();
        //获取功能导航
        //$nav = $this->auth_list();
        //获取栏目导航
        //$col = $this->column_list();
        //获取网站配置
        $site = db('Config')->order('id desc')->find();
        $ip = db('intercept')->field('rule,status')->order('id desc')->find();
        if (!$ip['status']) {
            check_ip($ip['rule']);
        }
        $mc_id = \session('mc_id');
        if($mc_id){
            $mch = new \app\admin\model\Mch();
            $info = $mch->get($mc_id);
            \session('is_vip',$info['is_vip']);
            $this->assign('user',$info);
            $this->assign('mc_id',$mc_id);
            $this->assign('is_vip',$info['is_vip']);
        }else{
            $this->assign('mc_id', 0);
            $this->assign('user',\session('_login'));
        }
        self::$setting =$site;
        session('_site',$site);
        $this->assign('site',$site);
    }

    /**
     * 获取栏目数据
     * @return \service\Array
     */
    protected function column_list(){
        $column = db("column")->where('status=0 and type!=6')->order('sort asc,id asc')->select();
        foreach ($column as $k => $v) {
            $column[$k]['col']=1;
        }
        $column= \service\Category::unlimitedForLevel($column);
        return $column;
    }

	public static function _sort_desc($list,$total=0,$p=1,$size=10,&$out=null){
        foreach ($list as $k => $v) {
            $list[$k]['sort_id'] = $total - ($p-1) * $size - $k;
        }
        $out = $list;
        return $list;
    }

    /**
     * [auth_list 获取功能栏目]
     * @return [type] [description]
     */
    protected function auth_list()
    {
        $gid  = session('_gid');
        $this->assign('gid', $gid);
        $nav=[];

        if ($gid!=-1 && !empty($gid)) {
            $_group = db('group')->field('id,title,power')->find($gid);
            $model = db('model')
                ->where('fid', 'eq', 0)
                ->where('status', 'eq', 0)
                ->where('id', 'in', $_group['power'])
                ->order('sort asc')
                ->select();
        } else {
            $model = db('model')->where('fid=0 and "show"=0 and status=0')->order('sort asc')->select();
        }

        foreach ($model as  $v) {
            $map['fid']=$v['id'];
            $map['status']=0;
            $map['show']=0;
            $child=db('model')->where($map)->order('sort asc,id asc')->select();
            foreach ($child as $k1 => $v1) {
                $child[$k1]['col']=0;
            }
            $v['child']=$child;
            $v['col']=0;
            $nav[]=$v;
        }
        return $nav;
    }

    /**
     * 判断登录状态
     */
    protected function check_priv(){
        if (!Session::has('_login') && $this->needLogin) {
            $this->redirect(Url('user/login'));
        } else {
            $user = session::get('_login');
            $user['username']=ucfirst($user['username']);
            $this->assign('user', $user);
        }
    }
    /**
     * @return array 获取当前系统信息
     */
    protected function _sys()
    {
        date_default_timezone_set("Etc/GMT-8");
        if (function_exists('gd_info')) {
            $gdInfo = gd_info();
            $gd_support = true;
            $gdv_version = $gdInfo['GD Version'];
        } else {
            $gd_support = false;
            $gdv_version  = '';
        }
        $sys=array(
            'os'=>PHP_OS,
            'os_all'=>php_uname('s'),
            //'server1'=>apache_get_version(),
            'server'=>php_sapi_name(),
            'think_ver'=>\think\facade\App::version(),
            'php'=> PHP_VERSION,
            'php_dir'=> DEFAULT_INCLUDE_PATH,
            'safe_mode'=>ini_get('safe_mode')?0:1,
            'gd'=>$gd_support,
            'gd_ver'=>$gdv_version,
            'mysql'=>self::get_version(),
            'mysql_size'=>self::get_mysql_db_size(),
            'file_size'=>ini_get("file_uploads") ? ini_get("upload_max_filesize") : "Disabled",
            'host'=>$_SERVER['SERVER_NAME'],
            'system_time' => date("Y-m-d", time()).'&nbsp;&nbsp;<span id="item-time">'.date('H:i:s', time()).'</span>',
            'cpu_num'=>self::cpu(),
            'meminfo'=>self::meminfo(),
            'net'=>self::net(),
            'server_lang'=>$_SERVER['HTTP_ACCEPT_LANGUAGE'],
            'server_point'=>$_SERVER['SERVER_PORT'],
            'memory_limit' => get_cfg_var("memory_limit") ? get_cfg_var("memory_limit") : '-',
        );
        return $sys;
    }

    protected static function cpu(){
        $str = shell_exec('more /proc/stat');
        $pattern = "/(cpu[0-9]?)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)/";
        preg_match_all($pattern, $str, $out);
        return count($out[1]);
    }

    protected static function meminfo(){
        $str = shell_exec('more /proc/meminfo');
        $pattern = "/(.+):\s*([0-9]+)/";
        preg_match_all($pattern, $str, $out);
        return [
            'total'=> $out[2][0],
            'used'=> $out[2][1],
            'free'=> $out[2][0] - $out[2][1],
            'pec'=> ($out[2][0] - $out[2][1])/$out[2][0] * 100 . '%'
        ];
//        echo "物理内存总量：".$out[2][0]."<br>";
//        echo "已使用的内存：".$out[2][1]."<br>";
//        echo "-----------------------------------------<br>";
//        echo "内存使用率：".(100*($out[2][0]-$out[2][1])/$out[2][0])."%<br>";
    }


    public static function net(){
        $str = shell_exec('more /proc/net/dev');
        $pattern = "/(eth[0-9]+):\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)/";
        preg_match_all($pattern, $str, $out);
//        for($n=0;$n<count($out[1]);$n++)
//        {
//            $out[1][$n]."：收到 ".$out[3][$n]." 个数据包，发送 ".$out[11][$n]." 个数据包<br>";
//        }
        return $out;
    }


    /**
     * 获取数据库版本
     * @return mixed
     */
    protected static function get_version(){
        $version = Db::query("select version() as ver");
        return $version[0]['ver'];
    }

    /**
     * mysql数据库大小
     * @return string
     */
    protected static function get_mysql_db_size(){
        $sql = "SHOW TABLE STATUS FROM ".config('database.database');
        $tblPrefix = config('database.prefix');
        if ($tblPrefix != null) {
            $sql .= " LIKE '{$tblPrefix}%'";
        }
        $row = Db::query($sql);
        $size = 0;
        foreach ($row as $value) {
            $size += $value["Data_length"] + $value["Index_length"];
        }
        return round(($size/1048576), 2).'M';
    }
    /**
     * [makeAttr 重置文章属性]
     * @param  [array] $resetAttr 重置的属性
     * @return [array] 返回重置的属性
     */
    protected function makeAttr($resetAttr)
    {
        $attr=array('com'=>0,'new'=>0,'head'=>0,'top'=>0,'img'=>0,'hot'=>0);
        foreach ($resetAttr as $k => $v) {
            $attr[$k]=1;
        }
        return $attr;
    }

    /**
    * 删除图片
    * @param string $url   图片地址
    * @return \think\response\Json
    */
    public function delete_image($url=''){
        if (strpos($url, '.')!==true) {
            $url = "." . $url;
        }
        if (!$url) {
            return json(['status'=>0,'msg'=>'图片地址不能为空']);
        }
        if (!is_file($url)) {
            return json(['status'=>0,'msg'=>'不是一个文件地址或地址不正确']);
        }
        if (!unlink($url)) {
            return json(['status'=>0,'msg'=>'删除失败,请重试']);
        }
        return json(['status'=>1,'msg'=>'删除成功']);
    }

    protected function _search($param=[]){
        $where=[];
        if (empty($param)) {
            $param = request()->param();
        }
        if (!empty($param['s_keywords'])) {
            $where['title']=['like',"%".$param['s_keywords']."%"];
        }
        if (!empty($param['s_status'])) {
            $where['status']=$param['s_status']>-1?$param['s_status']:'';
        }
        if (!empty($param['s_date'])) {
            $date = explode('-', $param['s_date']);
            $date[1] = "$date[1] 24:00";
            $where['date']=['between',[strtotime($date[0]),strtotime($date[1])]];
        }

        $this->assign('search', [
            's_keywords'=>!empty($param['s_keywords'])?$param['s_keywords']:'',
            's_date'=>!empty($param['s_date'])?$param['s_date']:'',
            's_status'=>!empty($param['s_status'])?$param['s_status']:''
        ]);
        return $where;
    }


    /**
     * 成功返回
     * @param string $msg
     * @param array $data
     * @param int $code
     * @param array $header
     * @param string $type
     * @return \think\Response
     */
    public function __s($msg='',$data=null,$code=200,$header=[],$type='json'){
        $data = is_object($data) ? $data->toArray() : $data;
        $msg = $msg ? $msg : 'success';
        $type = $type?$type : config('app.default_return_type');
        $data = (is_array($data) && $data) ? ['code'=>0,'msg'=>$msg,'data'=>$data] :
            ['code'=>0,'msg'=>$msg];
        return response($data,$code,$header,$type)->send();
    }

    /***
     * 失败返回
     * @param string $msg
     * @param array $data
     * @param int $code
     * @param array $header
     * @param $type
     * @return \think\Response
     */
    public function __e($msg='',$data=[],$code=200,$header=[],$type='json'){
        $data = is_object($data) ? $data->toArray() : $data;
        $msg = $msg ? $msg : 'error';
        $type = $type?$type : config('app.default_return_type');
        $data = (is_array($data) && $data) ? array_merge($data,['code'=>1]) : ['code'=>1,'msg'=>$msg];
        return response($data,$code,$header,$type)->send();
    }

    /**
     * 生成密码
     * @param $password
     * @return bool|string
     */
    protected static function _password($password){
        return substr(md5($password),10,20);
    }

    /**
     * 检测密码
     * @param string $input
     * @param string $out
     * @return bool
     */
    protected static function _checkPassword($input='',$out=''){
        return substr(md5($input),10,20) == $out;
    }
}
